﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FizzWare.NBuilder;
using mitasoft.Web.DAL.Model;
using System.Data;

namespace mitasoft.Web.DAL
{

    public interface IRepository
    {
        IQueryable<Book> Books { get; }

        Book GetBook(int id);
        void AddBook(Book book);
        void EditBook(Book book);
        void DeleteBook(int id);

        void SaveChanges();
    }

    public class Repository : IRepository
    {
        #region Test Method

        public static void Test()
        {
            using (SiteDataContext ctx = new SiteDataContext())
            {
                var book = new Model.Book() { Title = "Book 1", CoverUrl = "http://", AddDate = DateTime.Now };

                ctx.Books.Add(book);

                ctx.BookPosts.Add(new Model.BookPost
                {
                    Title = "Aaaa",
                    Description = "Asdasdasd",
                    Book = book
                });

                ctx.SaveChanges();
            }
        }

        #endregion

        #region Fields

        private SiteDataContext _ctx;

        #endregion

        #region Properties

       

        #endregion

        #region Ctor

        public Repository()
        {
            _ctx = new SiteDataContext();
        }

        #endregion

        public void SaveChanges()
        {
            _ctx.SaveChanges();
        }

        public IQueryable<Book> Books
        {
            get
            {
                return _ctx.Books.OrderBy(b => b.Id);
            }
        }

        public Book GetBook(int id)
        {
            return _ctx.Books.Where(b => b.Id == id).FirstOrDefault();
        }

        public void AddBook(Book book)
        {
            if (book == null)
            {
                throw new ArgumentNullException();
            }

            book.AddDate = DateTime.Now;

            _ctx.Books.Add(book);
        }

        public void EditBook(Book book)
        {
            if (book == null)
            {
                throw new ArgumentNullException();
            }

            _ctx.Books.Attach(book);
            _ctx.Entry(book).State = EntityState.Modified;
        }


        public void DeleteBook(int id)
        {
            var book = GetBook(id);
            _ctx.Books.Remove(book);
        }
    }
}
